using System;
using System.IO;
using NetworkCommsDotNet;
using Gtk;

namespace JiveMessengerLinux
{
    public partial class AddNewEmoticon : Gtk.Dialog
    {
        private const int MaxEmoticonHeigth = 70;
        private const int MaxEmoticonWidth = 200;
        private readonly string _customEmoticonFolder;
        public string CustomEmoticonPath { get; private set; }
        public string CustomEmoticonShortcut { get; private set; }
        // private byte[] _imgBytes;
        public FileInfo SourceFile { get; set; }
        private bool _tooBigGif;
        private bool Edit { get; set; }
        private string _originalShortCut = "";
        private Gtk.Image Emoticon { get; set; }
        public AddNewEmoticon(bool edit, string customEmoticonFolder)
        {
            this.Build();
            this._customEmoticonFolder = customEmoticonFolder;
            //this.EmoticonShortcuts = emoticonShortcuts;
            if (!Directory.Exists(customEmoticonFolder))
            {
                Directory.CreateDirectory(customEmoticonFolder);
            }
            this.Edit = edit;
            if (this.Edit)
            {
                this.Title = "Edit Emoticon";
            }
            this.lblImageError.Text = "";
            this.lblShortcutError.Text = "";
            Gdk.Color redColor = Gdk.Color.Zero;
            Gdk.Color.Parse("red", ref redColor);
            this.lblShortcutError.ModifyFg(StateType.Active, redColor);
            this.lblImageError.ModifyFg(StateType.Active, redColor);
        }
        protected void OnBnOkClicked(object sender, EventArgs e)
        {
            if (this.Edit)
            {

            }
            //else if (this.SourceFile.Extension != ".gif")
            //{
            //      ImageManipulation.SaveImageData(this._imgBytes, this.CustomEmoticonPath);
            //}
            else
            {
                try
                {
                    this.SourceFile.CopyTo(this.CustomEmoticonPath, true);
                }
                catch (Exception err)
                {
                    NetworkComms.Logger.ErrorException("Error adding emoticon", err);
                    MessageBox.Show(err.Message);
                    // this.DialogResult = false;

                    this.SourceFile = null;

                    return;
                }
            }
            this.SourceFile = null;

            //  this.DialogResult = true;
            this.Respond(ResponseType.Accept);
        }



        protected void OnBnBrowseClicked(object sender, EventArgs e)
        {

            var fd = new Gtk.FileChooserDialog("Select an emoticon", this, Gtk.FileChooserAction.Open, "Cancel", ResponseType.Cancel, "Open", ResponseType.Accept)
            {
                //Filter = "Image Files(*.BMP;*.JPG;*.GIF;*.PNG;)|*.BMP;*.JPG;*.GIF;*.PNG"
            };
            //fd.Filter.AddPattern("*.BMP");
            //fd.Filter.AddPattern("*.JPG");
            //fd.Filter.AddPattern("*.GIF");
            //fd.Filter.AddPattern("*.PNG");

            if (fd.Run() != (int)ResponseType.Accept) return;


            this.SourceFile = new FileInfo(fd.Filename);
            this.entryImageFile.Text = fd.Filename;
            fd.Destroy();
            this.CustomEmoticonPath = ResizeImage(this.SourceFile);
            if (this.SourceFile.Length > 1024 * 50) //50 kilobyte max
            {
                this.entryImageFile.Text = "";
                this.lblImageError.Text = "Max file size is 50kB";

                this.buttonOk.Sensitive = false;
                this.entryKeyboardShortcut.Sensitive = false;
            }
            if (this._tooBigGif)
            {
                this.entryImageFile.Text = "";
                this.lblImageError.Text = String.Format("GIF must be maximum {0}x{1} px.", MaxEmoticonWidth, MaxEmoticonHeigth);

                this.buttonOk.Sensitive = false;
                this.entryKeyboardShortcut.Sensitive = false;
            }
            else
            {
                if (!String.IsNullOrEmpty(this.entryKeyboardShortcut.Text))
                    this.buttonOk.Sensitive = true;
                this.lblImageError.Text = "";
                this.entryKeyboardShortcut.Sensitive = true;
                this.entryKeyboardShortcut.GrabFocus();
            }

            // SetImage(this.SourceFile.FullName);
            this.imgPreview = Emoticon;
        }
        public void SetText(string path, string shortcut)
        {
            if (this.Edit)
                this._originalShortCut = shortcut;
            this.entryImageFile.Text = path;
            this.entryKeyboardShortcut.Text = shortcut;
            this.CustomEmoticonPath = path;
            this.CustomEmoticonShortcut = shortcut;

        }
        private string ResizeImage(FileInfo file)
        {

            //byte[] imageBytes = ImageManipulation.LoadImageData(file.FullName);



            // decode the image such that its width is 120 and its 

            // height is scaled proportionally

            //   ImageSource imageSource = CreateImage(imageBytes, 120, 0);



            // OTHER OPTIONS

            this._tooBigGif = false;

            // the following will decode the image to its natural size

            //BitmapSource imageSource = ImageManipulation.CreateImage(imageBytes, 0, 0);

            Gtk.Image img = new Gtk.Image(file.FullName);

            if (img.Pixbuf.Width > MaxEmoticonWidth)
            {
                //imageSource = ImageManipulation.CreateImage(imageBytes, MaxEmoticonWidth, 0);
                this._tooBigGif = true;
            }

            if (img.Pixbuf.Height > MaxEmoticonHeigth)
            {
                // imageSource = ImageManipulation.CreateImage(imageBytes, 0, MaxEmoticonHeigth);
                this._tooBigGif = true;
            }

            // the following will decode the image such that its height

            // is 160 and its width is scaled proportionally

            // imageSource = CreateImage(imageBytes, 0, 160);



            // the following will decode the image to exactly 120 x 160 

            // imageSource = CreateImage(imageBytes, 120, 160);

            //  imageBytes = ImageManipulation.GetEncodedImageData(imageSource, file.Extension);

            string savePath = StaticMethods.CombinePath(this._customEmoticonFolder, file.Name);
            //   this._imgBytes = imageBytes;
            this.Emoticon = img;
            return savePath;

        }

        protected void OnButtonOkClicked(object sender, EventArgs e)
        {
            if (this.Edit)
            {

            }
            //else if (this.SourceFile.Extension != ".gif")
            //{
            //      ImageManipulation.SaveImageData(this._imgBytes, this.CustomEmoticonPath);
            //}
            else
            {
                try
                {
                    if (this.SourceFile != null)
                        this.SourceFile.CopyTo(this.CustomEmoticonPath, true);
                }
                catch (Exception err)
                {
                    NetworkComms.Logger.ErrorException("Error adding emoticon", err);
                    MessageBox.Show(err.Message);
                    // this.DialogResult = false;

                    this.SourceFile = null;

                    return;
                }
            }
            this.SourceFile = null;

            //  this.DialogResult = true;
            this.Respond(ResponseType.Accept);
        }

        protected void OnEntryKeyboardShortcutTextInserted(object o, TextInsertedArgs args)
        {
            ValidateShortcut();
        }
        private void ValidateShortcut()
        {

                string error;
                Gdk.Color redColor = Gdk.Color.Zero;
                Gdk.Color.Parse("red", ref redColor);
            bool isValid = StaticMethods.ValidateEmoticonShortcut(this.entryKeyboardShortcut.Text, this._originalShortCut, out error);
            Gtk.Application.Invoke (delegate {
            if (!isValid)
                {
                    if (this.entryKeyboardShortcut.Text.Length > 10)
                    {
                        this.entryKeyboardShortcut.Text = this.entryKeyboardShortcut.Text.Substring(0, 10);
                        // this.entryKeyboardShortcut.CursorHadjustment.;
                    }
                    // this.txtBoxImagePath.Text = "";
                    this.lblShortcutError.Text = error;
                    this.lblShortcutError.ModifyFg(StateType.Normal, redColor);
                    this.buttonOk.Sensitive = false;
                    //this.txtBoxShortcut.IsEnabled = false;
                }
                else if (!String.IsNullOrEmpty(this.entryKeyboardShortcut.Text) && !this._tooBigGif)
                {
                    this.lblShortcutError.Text = "";
                    this.buttonOk.Sensitive = true;
                    this.CustomEmoticonShortcut = this.entryKeyboardShortcut.Text;
                }
                else
                    this.buttonOk.Sensitive = false;
            });
        }
    }
}

